﻿using Microsoft.EntityFrameworkCore;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.ProjectManager;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.Extend.ModelExtend.ProjectExt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Project
{
    public class Project_Team_MainHandle
    {
        private readonly SJDBContext _context;

        public Project_Team_MainHandle(SJDBContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> CreateAsync(ProjectTeamMain entity)
        {
            try
            {
                _context.ProjectTeamMains.Add(entity);
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>Create", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<bool> UpdateAsync(ProjectTeamMain entity)
        {
            try
            {
                _context.Entry(entity).State = EntityState.Modified;
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>Update", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新特定内容
        /// </summary>
        /// <param name="entityExt"></param>
        /// <returns></returns>
        public async Task<bool> UpdateTeamMainSpecificContentAsync(ProjectTeamMainExtend entityExt)
        {
            try
            {
                ProjectTeamMain entity = entityExt.ExtMapToEntity<ProjectTeamMain, ProjectTeamMainExtend>();
                _context.Attach(entity);
                foreach (var property in entityExt.UpdateProperties)
                {
                    _context.Entry(entity).Property(property).IsModified = true;
                }
                await _context.SaveChangesAsync();
                return true;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>UpdateTeamMainSpecificContentAsync", ex);
                return false;
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="mainId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<bool> UpdateTeamMainStatusAsync(string mainId, int status)
        {
            try
            {
                var mains = await _context.ProjectTeamMains.AsNoTracking().Where(info => info.Id == mainId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"update project_team_main set status={status} where Id='{mainId}';");
                return count == mains.Count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>UpdateTeamMainSpecificContentAsync", ex);
                return false;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete(ProjectTeamMain entity)
        {
            try
            {
                _context.ProjectTeamMains.Remove(entity);
                return _context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>Delete", ex);
                return false;
            }
        }

        /// <summary>
        /// 根据主键删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByIdAsync(string id)
        {
            try
            {
                var entity = _context.ProjectTeamMains.Find(id);
                if (entity != null)
                {
                    _context.ProjectTeamMains.Remove(entity);
                    await _context.SaveChangesAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>DeleteById", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据项目id删除
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public async Task<bool> DeleteByProjectIdAsync(string projectId)
        {
            try
            {
                var mains = await _context.ProjectTeamMains.AsNoTracking().Where(info => info.ProjectId == projectId).ToListAsync();
                int count = _context.Database.ExecuteSqlRaw($"delete from project_team_main where ProjectId='{projectId}';");
                return mains.Count == count;
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>DeleteByProjectIdAsync", ex);
            }
            return false;
        }

        /// <summary>
        /// 根据ID获取实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ProjectTeamMainExtend> GetEntityByIdAsync(string id)
        {
            try
            {
                var query = from p in _context.ProjectMains
                            join main in _context.ProjectTeamMains on p.Id equals main.ProjectId
                            where main.Id == id //审批通过的项目和发起人是本人的
                            select new ProjectTeamMainExtend
                            {
                                Id = main.Id,
                                ProjectId = main.ProjectId,
                                ProjectName = p.ProjectName,
                                ManagerName = p.ManagerName,
                                Status = main.Status,
                                Mark = main.Mark,
                                StartTime = main.StartTime,
                                EndTime = main.EndTime,
                                AddTime = main.AddTime,
                                AddUserId = main.AddUserId,
                                EditTime = main.EditTime,
                                EditUserId = main.EditUserId
                            };
                return await query.FirstAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>GetEntityById", ex);
            }
            return new ProjectTeamMainExtend { };
        }

        /// <summary>
        /// 根据项目ID获取实体
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public async Task<ProjectTeamMainExtend> GetEntityByProjectIdAsync(string projectId)
        {
            try
            {
                var query = from p in _context.ProjectMains
                            join main in _context.ProjectTeamMains on p.Id equals main.ProjectId
                            where main.ProjectId == projectId //审批通过的项目和发起人是本人的
                            select new ProjectTeamMainExtend
                            {
                                Id = main.Id,
                                ProjectId = main.ProjectId,
                                ProjectName = p.ProjectName,
                                ManagerName = p.ManagerName,
                                Status = main.Status,
                                Mark = main.Mark,
                                StartTime = main.StartTime,
                                EndTime = main.EndTime,
                                AddTime = main.AddTime,
                                AddUserId = main.AddUserId,
                                EditTime = main.EditTime,
                                EditUserId = main.EditUserId
                            };
                return await query.FirstAsync();
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>GetEntityByProjectIdAsync", ex);
            }
            return new ProjectTeamMainExtend { };
        }

        /// <summary>
        /// 获取所有项目团队
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <param name="cprm"></param>
        /// <returns></returns>
        public async Task<(List<ProjectTeamMainExtend> mainExtends, int count)> GetProjectTeamMainsAsync(int pageNumber, int pageSize, string userId, Expression<Func<ProjectTeamMainExtend, bool>> cprm = null)
        {
            try
            {
                var query = from p in _context.ProjectMains
                            join main in _context.ProjectTeamMains on p.Id equals main.ProjectId into teamGroup
                            from main in teamGroup.DefaultIfEmpty()
                            where p.Status == 5 && (p.ManagerId == userId || p.AddUserId == userId) && (main == null || main.AddUserId == userId)//审批通过的项目和发起人是本人的
                            select new ProjectTeamMainExtend
                            {
                                Id = main.Id,
                                ProjectId = p.Id,
                                ProjectName = p.ProjectName,
                                ManagerName = p.ManagerName,
                                Status = main.Status,
                                Mark = main.Mark,
                                StartTime = main.StartTime,
                                EndTime = main.EndTime,
                                AddTime = main.AddTime,
                                AddUserId = main.AddUserId,
                                EditTime = main.EditTime,
                                EditUserId = main.EditUserId,
                                ProjectPassTime = p.EditTime
                            };
                // 如果提供了查询条件，则应用它
                if (cprm != null)
                {
                    query = query.Where(cprm);
                }

                // 总条数
                int count = await query.CountAsync();

                // 应用分页
                var skip = (pageNumber - 1) * pageSize;
                var pagedQuery = query.OrderBy(order => order.AddTime).Skip(skip).Take(pageSize);

                // 执行查询并返回结果
                var mainExtends = await pagedQuery.ToListAsync();

                return (mainExtends, count);
            }
            catch (Exception ex)
            {
                LogManager.WriteError("Project_Team_MainHandle=>GetProjectTeamMainsAsync", ex);
            }
            return (null, 0);
        }
    }
}
